<template>
  <div class="bottom-nav">
    <button @click="loadDensityData()">人口密度</button>
    <button>人口迁移分析</button>
    <button @click="echartShow()">图表展示</button>
    <button>
      <el-select
        v-model="selectvalue"
        placeholder="工具"
        filterable
        @change="toolSelect"
      >
        <el-option-group
          v-for="group in options"
          :key="group.label"
          :label="group.label"
        >
          <el-option
            v-for="item in group.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-option-group>
      </el-select>
    </button>
  </div>
</template>


<script>
import { Http } from "../model/index.js";
import { useCounterStore } from "../stores/counter.js";
import { HeatmapLayer } from "@antv/l7";
import { GaodeMap } from "@antv/l7-maps";
import {
  DrawEvent,
  DrawPolygon,
  DrawLine,
  DrawPoint,
  DrawRect,
} from "@antv/l7-draw";
export default {
  data() {
    return {
      scene: {},
      map: {},
      geodata: {},
      store: {},
      data: [],
      options: [
        {
          label: "查询",
          options: [
            {
              value: "select",
              label: "拉框查询",
            },
          ],
        },
        {
          label: "测量",
          options: [
            {
              value: "changdu",
              label: "长度",
            },
            {
              value: "mianji",
              label: "面积",
            },
            {
              value: "point",
              label: "点",
            },
          ],
        },
      ], //下拉框配置项
      selectvalue: "",
      isShow: true,
    };
  },
  mounted() {
    this.store = useCounterStore();
    this.scene = this.$scene;
    //初始化geosjon数据
    this.geodata = {
      type: "FeatureCollection",
      features: [],
    };

    //加载数据,转化为对象数组
    fetch("./src/assets/data/区县人口数据.txt")
      .then((res) => res.text()) // 这里用res.text()来解析文本数据
      .then((text) => {
        const lines = text.trim().split("\n");
        // 转化为对象数组
        const result = lines.map((line) => {
          const [address, num] = line.split(/\s+/);
          return { address, num: parseInt(num, 10) };
        });
        this.store.densityData = result;
        this.data = result;
        /*  result.map((item) => {
          try {
            if (item.address) {
              Http(item.address).then((res) => {
                if (res) {
                  const center = res.geocodes[0].location
                    .split(",")
                    .map((item) => parseFloat(item));

                  console.log(
                    `{type:'Feature',geometry:{type:'Point',coordinates:[${center}]},properties:{num:${item.num}}}`
                  );
                  this.geodata.features.push({
                    type: "Feature",
                    geometry: { type: "Point", coordinates: center },
                    properties: {
                      num: item.num,
                    },
                  });
                  //console.log(this.geodata.features);
                }
              });
            }
          } catch {
            console.log("请求结束阿");
          }
        }); */
        this.store.densityGeoData = this.geodata; //将数据存入pinia
        console.log(7777);
        Http("昆明").then((res) => {
          if (res) {
            console.log(res);
            const center = res.geocodes[0].location
              .split(",")
              .map((item) => parseFloat(item));
            console.log(center);
            console.log(`{'lng':${center[0]},'lat':${center[1]},'v':12}}`);

            this.geodata.features.push({
              type: "Feature",
              geometry: { type: "Point", coordinates: center },
              properties: {
                num: item.num,
              },
            });
            console.log(this.geodata.features, 123456);
            this.store.densityGeoData = this.geodata; //将数据存入pinia
          }
        });
      })
      .catch((error) => {
        console.error("Fetch error:", error);
      });
  },
  methods: {
    //加载热力图
    loadDensityData() {
      const scene = new Scene({
        id: "map",
        map: new GaodeMap({
          style: "light",
          center: [107.054293, 35.246265],
          zoom: 4.056,
        }),
      });
      scene.on("loaded", () => {
        fetch(
          "https://gw.alipayobjects.com/os/basement_prod/7359a5e9-3c5e-453f-b207-bc892fb23b84.csv"
        )
          .then((res) => res.text())
          .then((data) => {
            const layer = new HeatmapLayer({})
              .source(data, {
                parser: {
                  type: "csv",
                  x: "lng",
                  y: "lat",
                },
                transforms: [
                  {
                    type: "grid",
                    size: 20000,
                    field: "v",
                    method: "sum",
                  },
                ],
              })
              .shape("square")
              .style({
                coverage: 1,
                angle: 0,
              })
              .color(
                "count",
                [
                  "#0B0030",
                  "#100243",
                  "#100243",
                  "#1B048B",
                  "#051FB7",
                  "#0350C1",
                  "#0350C1",
                  "#0072C4",
                  "#0796D3",
                  "#2BA9DF",
                  "#30C7C4",
                  "#6BD5A0",
                  "#A7ECB2",
                  "#D0F4CA",
                ].reverse()
              );

            scene.addLayer(layer);
          });
      });
    },

    echartShow() {
      const myDiv = document.querySelector(".echarts");
      if (myDiv.style.display === "none") {
        myDiv.style.display = "block";
      } else {
        myDiv.style.display = "none";
      }
    },
    toolSelect(value) {
      if (value == "mianji") {
        const drawPolygon = new DrawPolygon(this.$scene, {
          areaOptions: {},
        });
        drawPolygon.enable();

        drawPolygon.on(DrawEvent.Change, (allFeatures) => {
          console.log(allFeatures);
        });
        drawPolygon.on(DrawEvent.Add, (newPoint) => {
          drawPolygon.disable();
        });
      }
      if (value == "changdu") {
        const drawLine = new DrawLine(this.$scene, {
          distanceOptions: {},
        });
        drawLine.enable();

        drawLine.on(DrawEvent.Change, (allFeatures) => {
          console.log(allFeatures);
        });
        drawLine.on(DrawEvent.Add, (newPoint) => {
          drawLine.disable();
        });
      }
      if (value == "point") {
        const drawPoint = new DrawPoint(this.$scene, {});
        drawPoint.enable();

        drawPoint.on(DrawEvent.Change, (allFeatures) => {
          console.log(allFeatures);
        });
        drawPoint.on(DrawEvent.Add, (newPoint) => {
          drawPoint.disable();
        });

        /* setInterval(() => {
          console.log(this.$scene.getZoom(), this.$scene.getCenter());
        }, 2000); */
      }
      if (value == "select") {
        const drawRect = new DrawRect(this.$scene, {});
        drawRect.enable();

        drawRect.on(DrawEvent.Change, (allFeatures) => {
          drawRect.destroy();
          let position = allFeatures[0].geometry.coordinates;
          // 转为turf
          let polygon = turf.polygon(position);
          // 点数据
          const features =
            this.$scene.getLayers()[0].layerSource.data.dataArray;
          features.forEach((feature) => {
            const coordinates_lng = feature.coordinates[0];
            const coordinates_lat = feature.coordinates[1];
            feature.coordinates = [coordinates_lng, coordinates_lat];
            // 获取坐标
            let position_point = feature.coordinates;
            // 转换为turf
            let point = turf.point(position_point);
            // 判断
            let result = turf.booleanContains(polygon, point);
            if (result) {
              if (feature.rainy) {
                store.info = "降雨量";
                store.searchLists.push({
                  date: feature.date,
                  name: feature.name,
                  data: parseInt(feature.rainy),
                  center: [feature.coordinates[0], feature.coordinates[1]],
                });
              } else if (feature.sun) {
                store.info = "光照强度";
                store.searchLists.push({
                  date: feature.date,
                  name: feature.name,
                  data: parseInt(feature.sun),
                  center: [feature.coordinates[0], feature.coordinates[1]],
                });
              } else if (feature.temperature) {
                store.info = "气温";
                store.searchLists.push({
                  date: feature.date,
                  name: feature.name,
                  data: parseInt(feature.temperature),
                  center: [feature.coordinates[0], feature.coordinates[1]],
                });
              }
            }
          });
          console.log(store.searchLists);
        });
        drawRect.on(DrawEvent.Add, () => {
          drawRect.disable();
        });
      } 
    },
  },
};
</script>

<style lang='scss' scoped>
.bottom-nav {
  bottom: 10px;
  position: fixed;
  left: 50%;
  display: flex;
  gap: 20px;
  transform: translateX(-50%);
  /* From Uiverse.io by biswacpcode */
  button {
    color: white;
    width: 200px;
    text-decoration: none;
    background-color: rgba(0, 0, 0, 0.5) !important;
    font-size: 20px;
    border: none;
    background: none;
    font-weight: 500;
    font-family: "Poppins", sans-serif;
    border-radius: 4px;
  }
  button::before {
    margin-left: auto;
  }

  button::after,
  button::before {
    content: "";
    width: 0%;
    height: 2px;
    background: #f6f8f7;
    display: block;
    transition: 0.5s;
  }

  button:hover::after,
  button:hover::before {
    width: 100%;
  }
}
</style>